#include "Arduino.h"

#define MAX_CMD_LEN 1024


//The setup function is called once at startup of the sketch
void setup()
{

	  Serial.begin(9600);

// Add your initialization code here
}

// The loop function is called in an endless loop
void loop()
{
	String cmd="";
	while (Serial.available() > 0)
	    {
		cmd += char(Serial.read());
	        delay(2);
	    }
	    if (cmd.length() > 0)
	    {
	        Serial.println(cmd);
	        parseCmd(cmd.c_str());
	        cmd = "";
	    }


}

void parseCmd(const char* cmd)
{
	if(cmd==NULL || strlen(cmd)==0)
		return;
	char str[MAX_CMD_LEN]={0};
	memcpy(str,cmd,min(MAX_CMD_LEN-1,strlen(cmd)));
	const char* delemiter="/";
	char* p=NULL;
	char order[128]={0};
	uint8_t pin=0;
	int value=0;
	if((p=strtok(str,delemiter)))
		sprintf(order,"%s",p);
	if((p=strtok(NULL,delemiter)))
		pin=0xff&atoi(p);
	if((p=strtok(NULL,delemiter)))
		value=atoi(p);
	if(strcmp(order,"w")==0)
	{
		pinMode(pin,OUTPUT);
		if(isAnalogPin(pin))
			analogWrite(pin,value);
		else
			digitalWrite(pin,value);
	}else if(strcmp(order,"r")==0){
		pinMode(pin,INPUT);
		value=isAnalogPin(pin)?analogRead(pin):digitalRead(pin);
		char buf[32]={0};
		sprintf(buf,"Pin %d ==> %d",pin,value);
		Serial.print(buf);
	}
}

bool isAnalogPin(uint8_t pin)
{
	switch(pin)
	{
		case A0:
		case A1:
		case A2:
		case A3:
		case A4:
		case A5:
		case A6:
		case A7:
			return true;
	}
	return false;
}
